package net.rlair.sbdemo.dao.mybatis.plugin;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;
import java.util.Properties;

/**
 * @author lixudong
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
public class SqlTimeLixudong implements Interceptor {

    private Properties properties;

    @Override
    public Object intercept(final Invocation invocation) throws Throwable {

        final long start = System.currentTimeMillis();
        try {
            return invocation.proceed();
        } finally {
            final StatementHandler statement = (StatementHandler) invocation.getTarget();
            final BoundSql sql = statement.getBoundSql();
            final long end = System.currentTimeMillis();
            final long executeTime = end - start;
            if (executeTime >= Long.parseLong(properties.getProperty("time"))) {
                System.out.println(String.format("本次sql耗时：%d , sql: \n%s", executeTime, sql.getSql()));
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }


    @Override
    public void setProperties(final Properties properties) {
        this.properties = properties;
    }
}
